﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace MockingBird.Simulator.Interceptors.Wcf.SimulatorHost
{
    public class Program
    {
        static void Main(string[] args)
        {
            Trace.WriteLine("Loading the Host application");
            Console.Title = "MockingBird Simulator Service";
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("Initializing the MockingBird SimulatorService...");
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("NOTE: If the ASMX/WCF service is active in a virtual dir on port 80, you can expect to see exceptions here");
            Console.WriteLine(Environment.NewLine);

            try
            {
                RunServiceHost();
            }
            catch (System.ServiceModel.AddressAlreadyInUseException aEx)
            {
                Console.WriteLine("ADDRESS/PORT SHARING EXCEPTION ENCOUNTERED");
                Console.WriteLine("Please stop the MockingBird IIS website and try again.");
                Console.WriteLine(aEx.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("EXCEPTION ENCOUNTERED");
                Console.WriteLine(e.ToString());
            }
            finally
            {
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();
            }


        }

        private static void RunServiceHost()
        {
            Trace.WriteLine("Running the service host");
            System.Net.ServicePointManager.ServerCertificateValidationCallback =
            ((sender, certificate, chain, sslPolicyErrors) => true);
            ServiceHost serviceHost = new ServiceHost(typeof(SimulatorService.SimulatorService));
            serviceHost.Open();
            string listenMessage = "The MockingBird SimulatorService is listening on the following addresses:";
            Trace.WriteLine(listenMessage);
            Console.WriteLine(listenMessage);
            foreach (ServiceEndpoint se in serviceHost.Description.Endpoints)
            {
                Console.WriteLine(se.Address.Uri.AbsoluteUri);
                Trace.WriteLine(se.Address.Uri.AbsoluteUri);
            }

            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();
            serviceHost.Close();
        }
    }
}
